package cn.edu.xjtu.UDP;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

import static javax.swing.WindowConstants.EXIT_ON_CLOSE;

/**
 * @author Hydrion-QLz
 * @date 2022-06-14 16:11
 * @description
 */
public class Client extends JPanel {
    JLabel loginState;
    static Socket socket;
    static BufferedWriter bw;
    static BufferedReader br;
    static DatagramSocket datagramSocket;
    static InetSocketAddress serverAddress;

    public static void main(String[] args) {
        try {
            datagramSocket = new DatagramSocket();
            int serverPort = 7777;
            String serverIp = "127.0.0.1";
            serverAddress = new InetSocketAddress(serverIp, serverPort);

            Client client = new Client();
            byte[] receive = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(receive, receive.length);
            do {
                datagramSocket.receive(receivePacket);
                System.out.println("接受到信息");
                String msg = formatString(new String(receivePacket.getData(), 0, receivePacket.getLength()));
                System.out.println(msg);
                client.loginState.setText(msg);
            } while (true);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String formatString(String str) {
        return " ".repeat((50 - str.length()) / 2) + str + " ".repeat((50 - str.length()) / 2);
    }

    public Client() {
        super(new FlowLayout(FlowLayout.CENTER));
        final int[] mode = {1};// 模式一为登录，模式二为注册

        Box titleBox = Box.createHorizontalBox();
        titleBox.add(Box.createVerticalStrut(100));
        titleBox.add(Box.createHorizontalStrut(10));
        JLabel title = new JLabel("登录");
        titleBox.add(title);
        Font font = new Font("宋体", Font.BOLD, 30);
        title.setFont(font);

        // 账号盒
        Box userNameBox = Box.createHorizontalBox();
        userNameBox.add(Box.createHorizontalStrut(10));
        userNameBox.add(Box.createVerticalStrut(30));

        // 密码盒
        Box passwdBox = Box.createHorizontalBox();
        passwdBox.add(Box.createHorizontalStrut(10));
        passwdBox.add(Box.createVerticalStrut(30));

        // 状态盒
        Box stateBox = Box.createHorizontalBox();
        stateBox.add(Box.createHorizontalStrut(5));
        stateBox.add(Box.createVerticalStrut(30));

        // 账号
        JLabel username = new JLabel("用户:");
        JTextField usernameText = new JTextField(20);

        // 密码
        JLabel password = new JLabel("密码:");
        JPasswordField passwordText = new JPasswordField(20);
        loginState = new JLabel();

        // 登录按钮
        JButton loginBtn = new JButton("登录");
        JButton registerBtn = new JButton("注册");

        // 登录按钮监听
        loginBtn.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    // 先把当前模式发过去,然后是对应的信息
                    System.out.println("发送信息");
                    String modeId = String.valueOf(mode[0]);
                    String userName = usernameText.getText();
                    String password = String.valueOf(passwordText.getPassword());
                    String msg = modeId + "-" + userName + "-" + password;
                    DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(StandardCharsets.UTF_8), msg.length(), serverAddress);
                    datagramSocket.send(datagramPacket);
                    System.out.println("发送成功");
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });

        registerBtn.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (mode[0] == 1) {
                    title.setText("注册");
                    loginBtn.setText("提交");
                    registerBtn.setText("返回");
                    passwordText.setText("");
                    usernameText.setText("");
                    loginState.setText("");
                    mode[0] = 2;
                } else {
                    mode[0] = 1;
                    title.setText("登录");
                    loginBtn.setText("登录");
                    registerBtn.setText("注册");
                    loginState.setText("");
                }
            }
        });


        this.add(titleBox);
        userNameBox.add(username);
        userNameBox.add(usernameText);
        passwdBox.add(password);
        passwdBox.add(passwordText);
        stateBox.add(loginState);

        this.add(userNameBox);
        this.add(passwdBox);
        this.add(loginBtn);
        this.add(registerBtn);
        this.add(stateBox);

        JFrame jFrame = new JFrame();
        jFrame.setTitle("在线聊天室");
        jFrame.setBounds(350, 150, 320, 300);
        jFrame.setLocationRelativeTo(null); // 设置该页面屏幕居中
        jFrame.setVisible(true);
        jFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        jFrame.add(this);
    }
}
